function elecPos=ecogVisOnBrainExtractElecPosFromMgrid(mgridFName)
% Extract the electrode positions from a *.mgrid file
%
% PURPOSE:
% Extract the electrode positions from a *.mgrid file.
% The *.mgrid files exported from brainImageSuite contain a lot of
% information irrelevant to visualization. This function will extracts and
% returns the electrode coordinates
%
% INPUT:
% mgridFName: The mgrid filename
%
% OUTPUT:
% elecPos:    The electrode positions

% To blame:
% 2012/10/11 JR wrote it

% open the text file and read it line by line
fH = fopen(mgridFName,'r');
count=0;
elecPos=[];
while 1
    lineBuf=fgetl(fH);
    if ~ischar(lineBuf) % end of file reached?
        break;
    end
    
    if strncmp(lineBuf,'# Electrode',11) % found an elexctrode desscripto block
        tmp=strfind (lineBuf,'Grid');
        if ~isempty(tmp) % A grid definition block
            disp([lineBuf(tmp:end) ' starts at electrode: ' num2str(count+1)])
        else % there should be elec coordinates in this block. Find them
            while 1 % try to find the position line
                lineBuf=fgetl(fH);
                if ~ischar(lineBuf) % end of file reached?
                    warning(['Unexpected end of file reached after reading coordinates of: ' num2str(count) 'electrodes']);
                    return; % leave the function and return what we have  so far.
                end
                if strncmp(lineBuf,'#- - - - -', 10)
                    warning(['No position was found for an electrode.'])
                    break; % We hit the end of an electrode definition block before we found electrode coordinates
                end
                if strncmp(lineBuf,'#Position',9)
                    lineBuf=fgetl(fH); % the electrode coordinates are in the next line
                    if ~ischar(lineBuf) % end of file reached?
                        warning(['Unexpected end of file reached after reading coordinates of: ' num2str(count) 'electrodes']);
                        return; % leave the function and return what we have  so far.
                    end
                    count=count+1;
                    elecPos(count,:)=str2num(lineBuf);
                    break; % we continue with the outer loop to find the next electrode definition bock
                end
            end
        end
    end
end
